package com.stb.client.dialog;

import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.stb.client.remote.UserServiceAsync;
import com.stb.shared.util.ListFactory;

public class RegisterUserDialog extends AbstractDialogBox {
	
	private final TextBox email;
	private final TextBox password;
	private final TextBox passwordCopy;
	private final UserServiceAsync userService;
	
	public RegisterUserDialog(UserServiceAsync userService) {
		super("Logon");
	    this.email = new TextBox();
	    this.password = new PasswordTextBox();
	    this.passwordCopy = new PasswordTextBox();
	    this.userService = userService;
	}

	@Override
	protected void setFocus() {
	    this.email.setFocus(true);
	}

	@Override
	protected List<DialogItem> getDialogItems() {
		return ListFactory.create(
			new DialogItem("Email:", email),
			new DialogItem("Password:", password),
			new DialogItem("Re-enter password:", passwordCopy)
		);
	}

	@Override
	protected ClickHandler getOKHandler() {
		return new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				userService.register(email.getText(), password.getText(), new AsyncCallback<Void>() {
					@Override
					public void onSuccess(Void result) {
						hide();
					}
					
					@Override
					public void onFailure(Throwable caught) {
						setError(caught.getMessage());
					}
				});
			}
		};
	}

	@Override
	protected boolean shouldEnableOk() {
		return this.password.getText().equals(this.passwordCopy.getText()) && super.shouldEnableOk();
	}
}
